package com.sharp.framework.utils;

import com.sharp.kernel.constant.err.ErrCodeSys;
import com.sharp.kernel.validate.Validator;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Collections;
import java.util.List;

/**
 * Title: PaginationUtil
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2020/8/20 15:02
 */
public class PaginationUtil {

    public static PaginationInfo getPaginationList(List<?> data, int nowPage, int pageSize) {
        Validator.assertNotEmpty(data, ErrCodeSys.PA_PARAM_NULL, "分页LIST");
        int totalPage = data.size();
        List<?> res = Collections.emptyList();
        int fromIndex = (nowPage - 1) * pageSize;
        if (fromIndex < data.size() && fromIndex > 0) {
            int toIndex = nowPage * pageSize;
            toIndex = Math.min(toIndex, totalPage);
            res = data.subList(fromIndex, toIndex);
        }

        return PaginationInfo.builder().data(res).nowPage(nowPage).pageSize(pageSize).totalCount(totalPage)
                .totalPage((data.size() + pageSize - 1) / pageSize).lastPage(Math.max(nowPage - 1, 1))
                .nextPage(nowPage >= totalPage ? totalPage : nowPage + 1).build();
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class PaginationInfo {
        private List<?> data;
        /**
         * 上一页
         */
        private int lastPage;
        /**
         * 当前页
         */
        private int nowPage;
        /**
         * 下一页
         */
        private int nextPage;
        /**
         * 每页条数
         */
        private int pageSize;
        /**
         * 总页数
         */
        private int totalPage;
        /**
         * 总数据条数
         */
        private int totalCount;
    }
}
